﻿using System;
using System.Collections;

namespace Library.Util
{
    public class ExceptionUtil
    {
        public static string ParseExceptions(Exception ex)
        {
            if (ex == null)
                return "";

            var _exceptions = new ArrayList();
            var _stackTrace = "";

            if (ex.StackTrace != null && ex.StackTrace.Contains("\n"))
            {
                var stackTrace = ex.StackTrace.Split('\n');
                for (var i = 0; i < stackTrace.Length; i++)
                {
                    stackTrace[i] = stackTrace[i].Replace("\r", "");
                    if (stackTrace[i].Trim().StartsWith("at NHibernate") || stackTrace[i].Trim().StartsWith("konum: NHibernate"))
                        continue;
                    if (stackTrace[i].Substring(stackTrace[i].Length - 2) == stackTrace[i].Substring(stackTrace[i].Length - 2).ToUpper())
                        _stackTrace += stackTrace[i].Trim() + "<br />";
                }
            }
            do
            {
                if (ex.GetType().Name == "TargetInvocationException" && ex.InnerException != null)
                {   }
                else
                {
                    if (ex.GetType() == typeof(NetException))
                    {
                        var exN = (NetException)ex;
                        _exceptions.Add(AppMessage.Get(exN.MessageText, exN.MessageParts));
                    }
                    else
                    {
                        _exceptions.Add(AppMessage.Get(ex.Message));
                    }
                }
                ex = ex.InnerException;
            } while (ex != null);

            var ext = "";
            for (var i = 0; i < _exceptions.Count; i++)
                ext += _exceptions[i] + "<br />";
            return ext;
        }
    }
}
